package com.example.demo.config;


import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by ace on 2017/9/8.
 */
@ControllerAdvice("com.example")
@ResponseBody
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(AccessDeniedException.class)
    public String handleAuthorizationException(AccessDeniedException e) {
        return "没有权限，请联系管理员授权";
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String argValidExceptionHandler(HttpServletResponse response, MethodArgumentNotValidException ex) {
        logger.error(ex.getMessage(), ex);
        response.setStatus(200);
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder("[");
        allErrors.forEach(e -> {
            stringBuilder.append(e.getDefaultMessage());
            stringBuilder.append(",");
        });
        stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length() - 1, "]");
        return stringBuilder.toString();
    }


}
